package com.baseDemo.web.interceptors;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.baseDemo.web.entity.AuthorityEntity;
import com.baseDemo.web.entity.UserEntity;
import com.baseDemo.web.server.SystemServer;

/**
 * 权限拦截器
 * @author xianwei
 *
 */
public class AuthorityInterceptor implements HandlerInterceptor{
	private final Logger logger = Logger.getLogger(getClass());
	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		String URL = request.getServletPath();
		HttpSession session = request.getSession();
		UserEntity userEntity = (UserEntity)session.getAttribute(SystemServer.getInstance().get("USERSESSION").toString());
		if(userEntity==null){
			request.getRequestDispatcher("login").forward(request, response);  
			return false;
		}else{
			Set<AuthorityEntity> authorities = userEntity.getAuthorities();
			for (AuthorityEntity authority : authorities) {
				if(URL.equals(authority.getAuthorityURL())){
					return true;
				}
			}
			logger.debug("-----no authority----");
			response.getWriter().write("{'success':'no authority'}");
			return false;
		}
	}

}
